﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;

namespace C
{
    public class ConfigController
    {
        public static List<Config> ListConfigCached = GetAll();

        public static string GetValue(E.Config config)
        {
            var row = ListConfigCached.Where(i => i.Name == config.ToString()).FirstOrDefault();
            if (row == null)
            {
                row = new Config();
                row.Name = config.ToString();
                row.Value = string.Empty;
                Insert(row);
            }
            return row.Value;
        }

        public static void Insert(Config a)
        {
            HCDataContext db = new HCDataContext();
            if (db.Configs.Where(i => i.Name == a.Name).Count() > 0)
            {
                return;
            }
            db.Configs.InsertOnSubmit(a);
            db.SubmitChanges();
            ListConfigCached = GetAll();
        }

        public static void Update(Config a, HCDataContext db)
        {
            db.SubmitChanges();
            ListConfigCached = GetAll();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            Config a = db.Configs.Where(
                ik => ik.ConfigID == id).First();
            db.Configs.DeleteOnSubmit(a);
            db.SubmitChanges();
            ListConfigCached = GetAll();
        }

        public static Config GetByID(int id, HCDataContext db)
        {
            return db.Configs.Where(
                ik => ik.ConfigID == id).FirstOrDefault();
        }

        public static Config GetByID(int id)
        {
            return ListConfigCached.Where(
                ik => ik.ConfigID == id).FirstOrDefault();
        }

        public static List<Config> GetAll()
        {
            HCDataContext db = new HCDataContext();
            return db.Configs.ToList();
        }
    }
}